package com.tongqu.utils;

import com.tongqu.po.Request;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.multipart.Attribute;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class HttpRequestParser {
    private FullHttpRequest fullReq;

    public FullHttpRequest getFullReq() {
        return fullReq;
    }

    public void setFullReq(FullHttpRequest fullReq) {
        this.fullReq = fullReq;
    }


    public HttpRequestParser() {

    }


    public Request parse() throws IOException {
        HttpMethod method = fullReq.method();

        Map<String, String> parmMap = new HashMap<>();
        Request request = null;
        if (HttpMethod.GET == method) {
            // 是GET请求
            QueryStringDecoder decoder = new QueryStringDecoder(fullReq.uri());
            //     String uri = decoder.uri();
            String path = decoder.path();

            decoder.parameters().entrySet().forEach(entry -> {
                // entry.getValue()是一个List, 只取第一个元素
                parmMap.put(entry.getKey(), entry.getValue().get(0));

            });
            request = new Request();
            request.setUri(path);
            request.setParmeter(parmMap);
            request.setMethod("GET");
        } else if (HttpMethod.POST == method) {
            // 是POST请求
            HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(fullReq);
            decoder.offer(fullReq);

            List<InterfaceHttpData> parmList = decoder.getBodyHttpDatas();

            for (InterfaceHttpData parm : parmList) {

                Attribute data = (Attribute) parm;
                parmMap.put(data.getName(), data.getValue());
            }
            request.setMethod("POST");
            request.setParmeter(parmMap);
            request.setUri(fullReq.uri());
        } else {

        }

        return request;
    }
}
